<template>
  <div class="mainbody">
    <!-- 标题 -->
    <el-row>
      <el-col :span="8" />
      <el-col :span="8">
        <div class="title">管理员登录</div>
      </el-col>
      <el-col :span="8" />
    </el-row>
    <!-- 表单 -->
    <el-row>
      <el-col :span="8" />
      <el-col :span="8">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码" prop="passowrd">
            <el-input v-model="ruleForm.passowrd" type="password" autocomplete="off" />
          </el-form-item>
          <el-form-item>
            <div class="login">
              <el-button type="primary" @click="submitForm(ruleFormRef)"> 登录 </el-button>
              <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="8" />
    </el-row>
  </div>
</template>
<script lang="ts" setup name="login">
import { reactive, ref } from 'vue'

import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const validateUser = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('用户名不能为空'))
  } else {
    if (ruleForm.username !== '') {
      if (!ruleFormRef.value) return
      // ruleFormRef.value.validateField('username')
    }
    callback()
  }
}
const validatePwd = (rule: any, value: any, callback: Function) => {
  if (value === '') {
    callback(new Error('密码不能为空'))
  } else {
    callback()
  }
}

const ruleForm = reactive({
  username: '',
  passowrd: '',
})

const rules = reactive<FormRules<typeof ruleForm>>({
  username: [{ validator: validateUser, trigger: 'blur' }],
  passowrd: [{ validator: validatePwd, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    console.log(valid)

    if (valid) {
      ElMessage.success('登录成功!!')

      //发起网络请求
    } else {
      ElMessage.primary('登录失败!!')
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
<style lang="scss" scoped>
html,
body {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.mainbody {
  background-color: #2d3a4b;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.title {
  margin-top: 200px;
  text-align: center;
  font-size: 40px;
  color: white;
}
.login {
  text-align: center;
  width: 100%;
  height: 100%;
}
</style>
